from django.db.models import Q, get_apps, get_models
from a115.utils.utils import flatten, listor_

def Q_for_model(M, q, search_fields = None):
    fieldnames = M._meta.get_all_field_names()
    search_fields = filter(lambda f: f in fieldnames, search_fields or (M.Search.search_fields if hasattr(M, "Search") else []))
    return listor_(Q(**{"%s__icontains" % f: q}) for f in search_fields if f in fieldnames) if search_fields else None

def search_model(M, q, search_fields = None):
    qobj = Q_for_model(M, q, search_fields)
    return M.objects.filter(qobj) if qobj else []

def list_models(): return flatten(get_models(app) for app in get_apps())

def search(q, search_fields=None): return flatten(search_model(M, q, search_fields) for M in list_models())
